import { defineStore } from 'pinia'
import { apiClient } from '@/api'
import router from '@/router'

interface UserInfo {
  userId: number
  username: string
  role: 'STUDENT' | 'TEACHER' | 'ADMIN'
}

// 创建一个只执行一次的初始化 Promise，防止重复初始化
let initPromise: Promise<void> | null = null

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || (null as string | null),
    user: JSON.parse(localStorage.getItem('user') || 'null') as UserInfo | null,
    isReady: false, // 新增：状态是否已从 localStorage 加载完毕
    returnUrl: '/',
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    isAdmin: (state) => state.user?.role === 'ADMIN',
    // --- 已修正 ---
    isTeacher: (state) => state.user?.role === 'TEACHER',
    isStudent: (state) => state.user?.role === 'STUDENT',
  },

  actions: {
    // 新增：初始化 Action，确保 token 和 user 信息被优先加载
    initialize() {
      if (!initPromise) {
        initPromise = new Promise((resolve) => {
          const token = localStorage.getItem('token')
          if (token) {
            this.token = token
            // 初始化时解析 token，如果失败也不强制登出，避免刷新页面就掉线
            this.decodeAndSetUser(token, false)
          }
          this.isReady = true
          console.log('Auth store initialized. User:', this.user)
          resolve()
        })
      }
      return initPromise
    },

    async login(loginRequest: { username: string; password: string }) {
      try {
        const response = await apiClient.post('/auth/login', loginRequest)
        const token = response.data.token

        this.token = token
        localStorage.setItem('token', token)
        this.decodeAndSetUser(token)

        await router.push(this.returnUrl || '/dashboard')
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }

    },

    async sendEmailVerificationEmail(email: string) {
      await apiClient.post('/auth/register/request', { email })
    },

    async checkUsernameExists(username: string) {
      const res = await apiClient.post('auth/register/request/check', { username })
      return res.data
    },

    async findAccounts(email: string) {
      const res = await apiClient.post('auth/find-account', { email })
      return res.data
    },

    async findPreciseAccount(request: { token: string }) {
      const res = await apiClient.post('/auth/find-account/account', request)
      return res.data
    },

    async resetPasswordByToken(request: {
      token: string
      username: string
      newPassword: string
      confirmPassword: string
    }) {
      const res = await apiClient.put('/auth/find-account/reset-password', request)
      return res.data
    },

    async register(registerRequest: object) {
      try {
        const response = await apiClient.post('/auth/register/verify', registerRequest)
        const token = response.data.token

        this.token = token
        localStorage.setItem('token', token)
        this.decodeAndSetUser(token)

        await router.push('/dashboard')
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      }
    },

    logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      initPromise = null
      router.push('/login')
    },

    decodeAndSetUser(token: string, forceLogoutOnError = true) {
      try {
        const payloadBase64 = token.split('.')[1]
        const decodedPayload = JSON.parse(atob(payloadBase64))
        this.user = {
          userId: decodedPayload.userId,
          username: decodedPayload.sub,
          role: decodedPayload.role,
        }
        localStorage.setItem('user', JSON.stringify(this.user))
      } catch (e) {
        console.error('解析 Token 失败', e)
        if (forceLogoutOnError) {
          this.logout()
        }
      }
    },
  },
})
